<template>
  <div>
    <el-transfer v-model="userRoles"
                 :data="roles"
                 @change="handleUserRoleChange"
                 :titles="['角色列表', '已有角色']"/>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {getRoleList} from "@/api/role.ts";
import {RoleData} from "@/type/RoleData.ts";
import {getUserRole} from "@/api/user.ts";
import {MainStore} from "@/store/MainStore.ts";

const props = defineProps(['userId'])
const roles = ref<Option[]>()
const userRoles = ref([] as Number[])
const mainStore = MainStore()

interface Option {
  key: number
  label: string
  disabled: boolean
}


onMounted(async () => {

  roles.value = await getRoles()
  userRoles.value = await getUserRolesId(props.userId)
})



const getRoles = async () => {

  const data = [] as Array<Option>
  const rawData = (await getRoleList()).data as RoleData[]

  rawData.forEach( item => {
    const option = {
      key: item.roleId,
      label: item.roleName
    } as Option

    data.push(option)
  })

  return data
}

const getUserRolesId = async (userId: number) => {

  const roleIdArray = [] as Array<Number>
  const rawData = (await getUserRole(userId)).data as RoleData[]

  rawData.forEach(item => {
    roleIdArray.push(item.roleId)
  })

  return roleIdArray
}

const handleUserRoleChange = () => {

  mainStore.userRoleIds = userRoles.value
}

</script>

<style lang="scss">

</style>